package com.tth.learn.addproperties.java;

/**
 * 线程通信的例子：使用两个线程打印1-100.线程1和线程2交替打印
 *
 * @Author tth
 * @Date 2022/11/1 17:52
 */
public class CommunicationTest {
    public static void main(String[] args) {
        Number number = new Number();

        Thread t1 = new Thread(number);
        t1.setName("线程1");

        Thread t2 = new Thread(number);
        t2.setName("线程2");

        t1.start();
        t2.start();

    }
}

class Number implements Runnable {

    private int num = 1;
    private Object obj = new Object();

    @Override
    public void run() {
        while (true) {
            synchronized (obj) {
                // 假如第一次进来的线程1。第一次notify()并没有唤醒任何线程。
                // 待线程1执行完wait()后,待线程1进入阻塞状态
                // 随后线程2进来。执行notify()，唤醒线程1
                obj.notify();
                if (num <= 100) {
                    System.out.println(Thread.currentThread().getName() + "_" + num);
                    num++;
                    try {
                        // 阻塞当前线程
                        obj.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    break;
                }
            }
        }
    }
}
